<?php

namespace app\api\service;

use think\facade\Db;

class CartService
{

    /**
     * 购物车所有价格
     */
    public static function cartTotal($param, $uid, $cids = '')
    {
        $msg = '';
        $code = 1;
        $list = Db::name('cart')
            ->alias('c')
            ->join('goods g', 'c.goods_id = g.id', 'left')
            ->where(['c.store_id' => $param['store_id'], 'g.delete_time' => null, 'c.uid' => $uid, 'c.delete_time' => 0])
            ->order('c.create_time', 'desc')
            ->field('c.id as cid,c.goods_id, c.sku_id,g.is_give_integral,g.is_limit_member,g.market_price,g.restricted_members,g.main_image as image,c.buy_num,g.goods_name,g.stock,g.is_subsidy,g.subsidy_price,g.sell_price,g.status');
        if ($cids) {
            $list = $list->where('c.id', 'in', $cids);
        }
        $list = $list->select()->toArray();

        $total = 0;
        $user_trade_id = 0;
        $total_give_interal = 0;
        foreach ($list as $k => $v) {
            $temp_stock = $v['stock'];
            $num = $v['buy_num'];
            if ($v['is_subsidy'] == 1) {
                $list[$k]['sell_price'] = $v['subsidy_price'];
            }

            if ($v['sku_id']) {
                $skuData = Db::name('goods_item')->where('id', $v['sku_id'])->find();
                $temp_stock = $skuData['stock'];
                $list[$k]['sell_price'] = $skuData['sell_price'];
                $list[$k]['image'] = $skuData['image'];
                $list[$k]['market_price'] = $skuData['market_price'];
            }
            $price = $list[$k]['sell_price'];
            $goods_total_amount = bcmul($price, $num, 2);

            $integral_scale = IntegralService::getGiveIntegralScale($param['store_id']);
            if ($integral_scale > 0 && $v['is_give_integral'] == 1) {
                $give_integral = floor($goods_total_amount * ($integral_scale / 100));
                $bs = OrderService::giveBirthdayPoint($uid); //判断是否生日
                if ($bs) {
                    $give_integral = bcmul($give_integral, $bs);
                }
                $total_give_interal += $give_integral;
            }

            $list[$k]['goods_total_amount'] = $goods_total_amount;
            if ($code == 1) {
                $user_trade_id = OrderService::findUserGrade($uid);
                if ($v['is_limit_member'] == 1 && !empty($v['restricted_members'])) {
                    $in = explode('-', $v['restricted_members']);
                    if (!in_array($user_trade_id, $in)) {
                        $code = 0;
                        $msg = '商品:' . $v['goods_name'] . '为会员专享,您还未成为会员';
                    }
                }
            }

            if ($code == 1) {
                if ($temp_stock < $num) {
                    $code = 0;
                    $msg = '商品:' . $v['goods_name'] . '库存不足';
                }
            }

            if ($code == 1) {
                if ($v['status'] != 1) {
                    $code = 0;
                    $msg = '商品:' . $v['goods_name'] . '已下架';
                }
            }
            $total = $total + (bcmul($price, $num, 2));
        }
        return [$list, $total, $code, $msg, $user_trade_id, $total_give_interal];
    }

    /**
     * 购物车列表
     */
    public static function cartList($param, $uid, $cids = '')
    {
        $list = Db::name('cart')
            ->alias('c');
        if ($cids) {
            $list = $list->where('c.id', 'in', $cids);
        }
        $list = $list->join('goods g', 'c.goods_id = g.id', 'left')
            ->where(['c.store_id' => $param['store_id'], 'g.delete_time' => null, 'c.uid' => $uid, 'c.delete_time' => 0])
            ->order('c.create_time', 'desc')
            ->withAttr('tags', function ($value) {
                if (empty($value)) {
                    return [];
                }
                return json_decode($value, true);
            })

            ->withAttr('main_image', function ($value) {
                return request()->domain() . $value;
            })->withAttr('goods_images', function ($value) {
            $imgs = [];
            $arr = json_decode($value, true);
            foreach ($arr as $v) {
                $imgs[] = request()->domain() . $v;
            }
            return $imgs;
        })->field('c.id,c.attr,c.sku_id,c.buy_num,g.id as gid,g.tags,g.status,g.goods_name,g.stock,g.main_image,g.spec_type,g.goods_images,g.market_price,g.sell_price')
            ->paginate(10)->each(function ($item) {
            if ($item['sku_id']) {
                $skuData = Db::name('goods_item')->where('id', $item['sku_id'])->withAttr('image', function ($value) {
                    return request()->domain() . $value;
                })->find();
                $item['stock'] = $skuData['stock'];
                $item['main_image'] = $skuData['image'];
                $item['market_price'] = $skuData['market_price'];
                $item['sell_price'] = $skuData['sell_price'];
            } else {
                $item['attr'] = '默认规格';
            }
            return $item;
        });
        return $list;
    }

    /**
     * 删除购物车
     */
    public static function delCart($data, $uid, $is_all = 0)
    {
        if ($is_all) {
            $rst = Db::name('cart')->where('uid', $uid)->update(['delete_time' => time()]);
        } else {
            $rst = Db::name('cart')->where('id', 'in',$data['cart_id'])->where('uid', $uid)->update(['delete_time' => time()]);
        }
        return $rst;
    }

    /**
     * 修改数量
     */
    public static function modifyNum($data, $num)
    {
        $type = $data['type'];
        if ($type == 1) {
            $rst = Db::name('cart')->where('id', $data['cart_id'])->where('delete_time', 0)->inc('buy_num', $num)->update();
        } else {
            $rst = Db::name('cart')->where('id', $data['cart_id'])->where('delete_time', 0)->dec('buy_num', $num)->update();
        }
        return $rst;
    }

    /**
     * 添加购物车
     */
    public static function add($data, $goods, $uid)
    {
        $spec_type = $goods['spec_type'];
        $attr = '';
        $sku_id = 0;
        if ($spec_type == 2) {
            $attr = $goods['attr'];
            $sku_id = $data['sku_id'];
        }
        $rest = Db::name('cart')->where(
            ['store_id' => $data['store_id'], 'uid' => $uid, 'delete_time' => 0, 'goods_id' => $data['goods_id'], 'sku_id' => $data['sku_id']]
        )->find();
        if (!empty($rest)) {
            $rst = Db::name('cart')->where('id', $rest['id'])->inc('buy_num', $data['buy_num'])->update();
        } else {
            $rst = Db::name('cart')->insert([
                'store_id' => $data['store_id'], 'uid' => $uid, 'goods_id' => $data['goods_id'], 'create_time' => time(),
                'attr' => $attr, 'image' => $goods['main_image'], 'sku_id' => $sku_id, 'buy_num' => $data['buy_num'],
            ]);
        }
        return $rst;
    }
}
